﻿using BLL;
using DAL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace WeChat.WxPayAPI.WeHelper
{
    public class WeHelper
    {
        static SetBasicInfoBLL baseInfo = new SetBasicInfoBLL();
        static DataTable dt2 = baseInfo.getWechatBaseInfo();
        public static string appId
        {
            get
            {
                return dt2.Rows[0]["appId"] == null ? "" : dt2.Rows[0]["appId"].ToString();//微信开发者appId
            }
        }
        private static string secret
        {
            get
            {
                return dt2.Rows[0]["appSecret"] == null ? "" : dt2.Rows[0]["appSecret"].ToString();//微信开发者secret
            }
        }

        private static readonly string tokenUrl = "https://api.weixin.qq.com/cgi-bin/token";

        private static readonly string ticket = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        public static string GetAccessToken()
        {
            if (HttpRuntime.Cache.Get("AccessToken") == null)
            {
                StringBuilder sbUrl = new StringBuilder();
                sbUrl.AppendFormat(tokenUrl);
                sbUrl.AppendFormat("?grant_type=client_credential");
                sbUrl.AppendFormat("&appid={0}", appId);
                sbUrl.AppendFormat("&secret={0}", secret);
                using (WebClient client = new WebClient())
                {
                    client.Encoding = Encoding.UTF8;
                    string data = client.UploadString(sbUrl.ToString(), string.Empty);
                    var result = JObject.Parse(data);
                    if (result["access_token"] != null && result["access_token"].Value<string>() != string.Empty)
                    {
                        string token = result["access_token"].Value<string>();
                        HttpRuntime.Cache.Insert("AccessToken", token, null, DateTime.Now.AddSeconds(7200), System.Web.Caching.Cache.NoSlidingExpiration);
                        return token;
                    }
                    else
                        throw new Exception(data);
                }
            }
            else
            {
                return HttpRuntime.Cache.Get("AccessToken").ToString();
            }
        }
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static string GetTicket(string accessToken)
        {
            if (HttpRuntime.Cache.Get("Ticket") == null)
            {
                StringBuilder sbUrl = new StringBuilder();
                sbUrl.AppendFormat(ticket);
                sbUrl.AppendFormat("?access_token={0}", accessToken);
                sbUrl.AppendFormat("&type=jsapi");
                using (WebClient client = new WebClient())
                {
                    client.Encoding = Encoding.UTF8;
                    string data = client.UploadString(sbUrl.ToString(), string.Empty);
                    var result = JObject.Parse(data);
                    if (result["ticket"] != null && result["ticket"].Value<string>() != string.Empty)
                    {
                        string ticket = result["ticket"].Value<string>();
                        HttpRuntime.Cache.Insert("Ticket", ticket, null, DateTime.Now.AddSeconds(7200), System.Web.Caching.Cache.NoSlidingExpiration);
                        return ticket;
                    }
                    else
                        throw new Exception(data);
                }
            }
            else
            {
                return HttpRuntime.Cache.Get("Ticket").ToString();
            }
        }
        /// <summary>
        /// 获取签名
        /// </summary>
        /// <param name="timestamp"></param>
        /// <param name="noncestr"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetSignature(string timestamp, string noncestr, string url)
        {
            string string1 = "jsapi_ticket=" + GetTicket(GetAccessToken()) + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
            ApplicationLog.Write("string1:"+ string1);
            //使用sha1加密这个字符串
            return SHA1(string1);
        }


        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <returns></returns>
        public static string CreateNonceStr()
        {
            int length = 16;
            string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            string str = "";
            var rad = new Random();
            for (int i = 0; i < length; i++)
            {
                str += chars.Substring(rad.Next(0, chars.Length - 1), 1);
            }
            return str;
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string SHA1(string str)
        {
#pragma warning disable CS0618 // “FormsAuthentication.HashPasswordForStoringInConfigFile(string, string)”已过时:“The recommended alternative is to use the Membership APIs, such as Membership.CreateUser. For more information, see http://go.microsoft.com/fwlink/?LinkId=252463.”
            str = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(str, "SHA1").ToString();
#pragma warning restore CS0618 // “FormsAuthentication.HashPasswordForStoringInConfigFile(string, string)”已过时:“The recommended alternative is to use the Membership APIs, such as Membership.CreateUser. For more information, see http://go.microsoft.com/fwlink/?LinkId=252463.”
            return str.ToLower();
        }

        /// <summary>
        /// 生成时间戳
        /// </summary>
        /// <returns></returns>
        public static string CreateTimestamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            string timestamp = Convert.ToInt64(ts.TotalSeconds).ToString();
            return timestamp;
        }
    }
}